package com.bjsxt.config.shiro;

import com.alibaba.fastjson.JSON;
import com.bjsxt.constants.HttpStatus;
import com.bjsxt.vo.AjaxResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:liao
 * @Description:TODO 重写shiro的authc过滤器
 * @date:2020/11/19
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {
    /**
     * 在访问controller时进行认证
     * 如果认证不通过则会被该方法拦截
     * @param request
     * @param response
     * @return true表示继续往下执行其他过滤器
     *          false表示该请求已经被此过滤器处理 不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //设置响应字符集
        httpServletResponse.setCharacterEncoding("UTF-8");
        //设置响应体
        httpServletResponse.setContentType("application/json");
        //设置响应数据
        AjaxResult ajax = AjaxResult.fail();
        ajax.put("code", HttpStatus.UNAUTHORIZED);
        ajax.put("msg","登录认证失效，请重新登录!");
        //响应
        httpServletResponse.getWriter().write(JSON.toJSONString(ajax));
        return false;
    }
}
